import {Component, OnInit} from '@angular/core';
import {Service} from '../service/service';
import {Icon} from './iconData';
import {NzMessageService} from 'ng-zorro-antd/message';

export interface TreeNodeInterface {
  children: any;
  _id: string;
  sort: number;
  module_name?: string;
  type?: number;
  action_name?: string;
  module_id?: string;
  url: string;
  description: string;
  expand?: boolean;
  items?: TreeNodeInterface[];
  parent?: TreeNodeInterface;
}

@Component({
  selector: 'app-access',
  templateUrl: './access.component.html',
  styleUrls: ['./access.component.scss']
})
export class AccessComponent implements OnInit {
  private visible = false;
  private edit: object = {};
  private typeChoose: Array<object> = [
    {name: '模块', value: 1},
    {name: '菜单', value: 2},
    {name: '操作', value: 3},
  ];
  private methodData: Array<object> = [
    {name: 'GET', value: 'GET'},
    {name: 'POST', value: 'POST'},
    {name: 'PUT', value: 'PUT'},
    {name: 'DELETE', value: 'DELETE'},
  ];
  private iconData = Icon.iconData;

  constructor(private service: Service, public msg: NzMessageService) {
    this.getAccess();
    this.getAccessModule();
  }

  private list: Array = [];
  private accessModule = [];
  private mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};

  async getAccess() {
    const result: object = await this.service.getAccess(null);
    this.list = result.data.data;
    this.list = this.format(this.list);
    console.log(this.list);
  }

  format(data) {
    data.forEach((v, i) => {
      v.children = v.items;
      v.key = `${i + 1}`;
      v.children.forEach((c, idx) => {
        c.key = `${i + 1}-${idx + 1}`;
      });
    });
    console.log(this.list);
    data.forEach(item => {
      this.mapOfExpandedData[item.key] = this.convertTreeToList(item);
    });
    return data;
  }

  async getAccessModule() {
    const result: object = await this.service.getAccessModule(null);
    this.accessModule = result.data.data;
  }

  collapse(array: TreeNodeInterface[], data: TreeNodeInterface, $event: boolean): void {
    if (!$event) {
      if (data.children) {
        data.children.forEach(d => {
          const target = array.find(a => a.key === d.key)!;
          target.expand = false;
          this.collapse(array, target, false);
        });
      } else {
        return;
      }
    }
  }

  convertTreeToList(root: TreeNodeInterface): TreeNodeInterface[] {
    const stack: TreeNodeInterface[] = [];
    const array: TreeNodeInterface[] = [];
    const hashMap = {};
    stack.push({...root, level: 0, expand: false});
    while (stack.length !== 0) {
      const node = stack.pop()!;
      this.visitNode(node, hashMap, array);
      if (node.children) {
        for (let i = node.children.length - 1; i >= 0; i--) {
          stack.push({...node.children[i], level: node.level! + 1, expand: false, parent: node});
        }
      }
    }
    return array;
  }

  visitNode(node: TreeNodeInterface, hashMap: { [key: string]: boolean }, array: TreeNodeInterface[]): void {
    if (!hashMap[node.key]) {
      hashMap[node.key] = true;
      array.push(node);
    }
  }

  ngOnInit(): void {

  }

  showModal(data) {
    if (data) {
      if (data.type === 1) {
        data.module_id = '0';
      }
      this.edit = data;
    } else {
      this.edit = {
        module_name: '', action_name: '', type: 1, url: '', sort: 100, description: '', module_id: '0', method: 'GET', icon: ''
      };
    }
    console.log(this.edit);
    this.visible = true;
  }

  async update() {
    console.log(this.edit);
    if (this.edit._id) {
      const {_id, module_name, module_id, action_name, type, url, sort, description, method, icon} = this.edit;
      const data = {
        _id, module_name, module_id, action_name, type, url, sort, description, method, icon
      };
      const result: object = await this.service.editAccess(data);
      console.log(result);
      if (result.data.code === 200) {
        this.msg.info('修改权限信息成功');
        this.getAccess();
      }
    } else {
      const {module_name, module_id, action_name, type, url, sort, description, method, icon} = this.edit;
      const data = {
        module_name, module_id, action_name, type, url, sort, description, method, icon
      };
      const result: object = await this.service.addAccess(data);
      console.log(result);
      if (result.data.code === 200) {
        this.msg.info('添加权限信息成功');
        this.getAccess();
      }
    }
    this.close();
  }

  close(): void {
    this.edit = {};
    this.visible = false;
  }

  cancel(): void {

  }

  async confirm(_id): void {
    const data = {_id};
    const result: object = await this.service.deleteAccess(data);
    console.log(result);
    if (result.data.code === 200) {
      this.msg.info('删除权限信息成功');
      this.getAccess();
    }
  }

  changeType(v) {
    console.log(v);
    if (v === 1) {
      this.edit?.module_id = '0';
    }
  }
}
